package org.smart4j.framework.Util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public final class ClassUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);

    /**
     * 获取类加载器
     * @return
     */
    public static ClassLoader getClassLoader(){
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     * @param className
     * @param isInitialized: true表示执行类的静态代码块，为提高加载性能，可将其置为false
     * @return
     */
    public static Class<?> loadClass(String className, boolean isInitialized){
        Class<?> cls;
        try {
            cls = Class.forName(className,isInitialized,getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("加载类失败",e);
            throw new RuntimeException(e);
        }
        return cls;
    }

    /**
     * 加载类
     * @param className
     * @return
     */
    public static Class<?> loadClass(String className){
        Class<?> cls;
        try {
            cls = Class.forName(className,true,getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("加载类失败",e);
            throw new RuntimeException(e);
        }
        return cls;
    }

    /**
     * 获取指定包名下的所有类
     * @param packageName
     * @return
     */
    public  static Set<Class<?>> getClassSet(String packageName){
        //根据包名将其转换为文件路径，读取class文件或者jar文件，获取指定的类名去进行加载
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        Enumeration<URL> urls;
        try {
            urls = getClassLoader().getResources(packageName.replace(".","/"));
        } catch (IOException e) {
            LOGGER.error("获取类失败",e);
            throw new RuntimeException(e);
        }

        while (urls.hasMoreElements()){
            URL url = urls.nextElement();
            if (url == null){
                return classSet;
            }
            String protocol = url.getProtocol();
            if ("file".equals(protocol)){
                String packagePath = url.getPath().replaceAll("%20","");
                addClass(classSet,packagePath,packageName);
            }else if ("jar".equals(protocol)){
                JarFile jarFile;
                try {
                    JarURLConnection jarURLConnection = (JarURLConnection)url.openConnection();
                    if (jarURLConnection == null){
                        return classSet;
                    }
                    jarFile = jarURLConnection.getJarFile();
                    if (jarFile == null){
                        return classSet;
                    }
                } catch (IOException e) {
                    LOGGER.error("获取jar包中的类失败",e);
                    throw new RuntimeException(e);
                }

                Enumeration<JarEntry> jarEntries =  jarFile.entries();
                while (jarEntries.hasMoreElements()){
                    JarEntry jarEntry = jarEntries.nextElement();
                    String jarEntryName = jarEntry.getName();
                    if (jarEntryName.endsWith(".class")){
                        String className = jarEntryName.substring(0,jarEntryName.lastIndexOf("."))
                                .replace("/",".");
                        doAddClass(classSet,className);
                    }
                }
            }
        }

        return classSet;
    }

    /**
     * 将package下的file和directory迭代，将class文件放入classSet中。
     * @param classSet
     * @param packagePath
     * @param packageName
     */
    private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            public boolean accept(File file) {
                //需要找到以.class结尾的文件或者文件夹
                return (file.isFile() && file.getName().endsWith(".class") || file.isDirectory());
            }
        });

        for (File file : files){
            String fileName = file.getName();
            if (file.isFile()){
                String className = fileName.substring(0,fileName.lastIndexOf("."));
                if (StringUtils.isNoneEmpty(packageName)){
                    className = packageName + "." + className;
                }
                doAddClass(classSet,className);
            }else{
                String subPackagePath = fileName;
                if (StringUtils.isNoneEmpty(packagePath)){
                    subPackagePath = packagePath + "/" + subPackagePath;
                }

                String subPackageName = fileName;
                if (StringUtils.isNoneEmpty(packageName)){
                    subPackageName = packageName + "." + subPackageName;
                }
                //迭代
                addClass(classSet,subPackagePath,subPackageName);
            }
        }
    }

    /**
     * 通过className加载类，并放入集合中
     * @param classSet
     * @param className
     */
    private static void doAddClass(Set<Class<?>> classSet, String className) {
        Class<?> cls = loadClass(className,false);
        classSet.add(cls);
    }


}
